package so.wy.servicecenter.businessbed.manager.normal;

import cn.binarywang.wx.miniapp.api.WxMaMsgService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.constant.WxMaConstants;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import so.wdl.framework.core.thread.ThreadUtil;
import so.wy.servicecenter.base.frame.manager.AbstractManager;
import so.wy.servicecenter.businessbed.dao.enums.StatusPushEnum;
import so.wy.servicecenter.businessbed.dao.enums.TypePushEnum;
import so.wy.servicecenter.businessbed.dao.rdb.order.order.OrderDO;
import so.wy.servicecenter.businessbed.dao.rdb.push_history.PushHistoryDAO;
import so.wy.servicecenter.businessbed.dao.rdb.push_history.PushHistoryDO;
import so.wy.servicecenter.businessbed.dao.rdb.rent_user.RentUserDO;
import so.wy.servicecenter.businessbed.extend.UserAppOutManager;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Scope("prototype")
public class WxMiniMsgManager extends AbstractManager {
    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private UserAppOutManager userAppOutManager;

    @Autowired
    private PushHistoryDAO pushHistoryDAO;


    // 发送订单成功相关消息
    public void sendOrderProcessingMsg(RentUserDO rentUser, OrderDO order) {
        ThreadUtil.execAsync(() -> {
            WxMaMsgService msgService = wxMaService.getMsgService();

            //进行消息填充
            List<WxMaSubscribeMessage.Data> msgData = new ArrayList<>();

            WxMaSubscribeMessage subscribeMessage = WxMaSubscribeMessage.builder()
                    .templateId("")
                    .miniprogramState(WxMaConstants.MiniprogramState.DEVELOPER)
                    .page("")
                    .toUser(userAppOutManager.getUserOpenId(rentUser.getUserId()))
                    .data(msgData)
                    .build();

            try {
                msgService.sendSubscribeMsg(subscribeMessage);
                saveMsg(rentUser, "订单创建成功", msgData, StatusPushEnum.SUCCESS);
            } catch (WxErrorException e) {
                logger.error(e.getMessage());
                saveMsg(rentUser, "订单创建成功", msgData, StatusPushEnum.FAIL);
            } catch (RuntimeException run) {
                saveMsg(rentUser, "订单创建成功", msgData, StatusPushEnum.FAIL);
            }
        });
    }


    // 发送订单成功相关消息
    public void sendOrderFinshMsg(RentUserDO rentUser, OrderDO order) {
        ThreadUtil.execAsync(() -> {
            WxMaMsgService msgService = wxMaService.getMsgService();

            //进行消息填充
            List<WxMaSubscribeMessage.Data> msgData = new ArrayList<>();

            WxMaSubscribeMessage subscribeMessage = WxMaSubscribeMessage.builder()
                    .templateId("")
                    .miniprogramState(WxMaConstants.MiniprogramState.DEVELOPER)
                    .page("")
                    .toUser(userAppOutManager.getUserOpenId(rentUser.getUserId()))
                    .data(msgData)
                    .build();

            try {
                msgService.sendSubscribeMsg(subscribeMessage);
                saveMsg(rentUser, "订单完成", msgData, StatusPushEnum.SUCCESS);
            } catch (WxErrorException e) {
                logger.error(e.getMessage());
                saveMsg(rentUser, "订单完成", msgData, StatusPushEnum.FAIL);
            }
        });
    }

    private void saveMsg(RentUserDO rentUser, String title, List<WxMaSubscribeMessage.Data> msgData,
                         StatusPushEnum statusPush) {
        PushHistoryDO pushHistoryDO = new PushHistoryDO();
        pushHistoryDO.setPushTime(new Date());
        pushHistoryDO.setPushType(TypePushEnum.MINIO_SUBMSG.getCode());
        pushHistoryDO.setPushSender("系统平台");
        pushHistoryDO.setPushReceiver(rentUser.getRentUserName() + "(" + rentUser.getRentUserPhone() + ")");
        pushHistoryDO.setPushTitle(title);
        pushHistoryDO.setPushContent(getMsgContent(msgData));
        pushHistoryDO.setPushStatus(statusPush.getCode());
        pushHistoryDO.setRentUserId(rentUser.getRentUserId());

        pushHistoryDAO.insert(pushHistoryDO);
    }

    private String getMsgContent(List<WxMaSubscribeMessage.Data> msgData) {
        StringBuilder stringBuilder = new StringBuilder();
        for (WxMaSubscribeMessage.Data data : msgData) {
            stringBuilder.append(data.getValue()).append(":").append(data.getValue()).append(";");
        }

        return stringBuilder.toString();
    }
}
